package App.Service;

/**
 * Created by xw on 2019/4/26.
 */

import App.Model.Account.CrmUser;
import App.Model.Account.CrmWebLogin;
import App.Model.Account.WebLoginGetTokenResponse;
import App.Model.JPush.JPushCustomerContent;
import App.Model.Xinge.XinGeCustomerContent;
import App.Repository.AccountRepository;
import App.Repository.FriendRepository;
import App.Repository.QRCodeRepository;
import App.Tencent.SignatureManager;
import App.Utility.CommonHelper;
import App.Utility.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;


//import  App.Utility.MatrixToImageWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class QRCodeServcie {

    @Autowired
    private CommonHelper _commonHelper;

    @Autowired
    private QRCodeRepository _repository;

    @Autowired
    private FriendRepository _friendRepository;

    @Autowired
    private XingeService _xingeService;

    @Autowired
    private JPushService _jPushService;

    public String generateQRCode(String text, int width, int height, String format, String key) throws Exception {

        Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        String pathName = _commonHelper.getUploadFilePath() + key + ".png";
        File outputFile = new File(pathName);
        MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);

        //write record to data base
        _repository.insertWebLoginRecord(key);

        return pathName;
    }


    @Resource
    private TecentIMService _imService;


    public WebLoginGetTokenResponse geLogintToken(String _key) {
        String _token = "";
        int _userid=0;
        long _sdkid = _imService.getSDKId();
        String _winKeyPath = _imService.getWinKeyPath();
        String _linuxKeyPath = _imService.getLinuxKeyPath();

        List<CrmWebLogin> _tokens = _repository.getToken(_key);
        if(_tokens!=null&&_tokens.size()>0){
            CrmWebLogin _webLogin=_tokens.get(0);
            _userid= _webLogin.getUserid();
            _token=_webLogin.getToken();
        }
        String _sig = SignatureManager.getSignatureAdv(_sdkid, _winKeyPath, _linuxKeyPath, Integer.toString(_userid), _imService.getSigType(), _imService.getSecuretKey());
        String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

        WebLoginGetTokenResponse _response = new WebLoginGetTokenResponse();
        _response.setToken(_token);
        _response.setSig(_sig);
        _response.setUserid(_userid);
        _response.setServertime(timeStamp);
        return _response;
    }

    public List<CrmWebLogin> getToken(String _key) {
        return   _repository.getToken(_key);
    }
    public int updateToken(String _key, String _token,int userid) {
        return _repository.updateToken(_key, _token,userid);
    }

    public int confirmReWebLogin(String _key) {
        return _repository.confirmReWebLogin(_key);
    }

    public boolean isWebReLoginConfirmed(String _key) {

        boolean _isConfirmed = false;
        List<CrmWebLogin> _lists = _repository.isWebReLoginConfirmed(_key);
        if (_lists != null && _lists.size() > 0) {
            _isConfirmed = _lists.get(0).getIsconfirmed();

            if(_isConfirmed){

                _repository.setWebReLoginUnConfirmed(_key);

            }
        }
        return _isConfirmed;
    }

    public CrmWebLogin getWebReLoginConfirmed(String _key) {
        boolean _isConfirmed = false;
        List<CrmWebLogin> _lists = _repository.isWebReLoginConfirmed(_key);
        if(_lists != null && _lists.size() > 0)
            return _lists.get(0);
        return  null;
    }

    public boolean pushWebLogin(String _key, int userid) throws Exception {

        boolean _hasPushed = true;
        List<String> _userids = new ArrayList<>();
        _userids.add(Integer.toString(userid));

        String _title = "web端登陆";
        String _message ="请在APP上确认登录web端";

        //极光推送
        Collection<String> alias = new LinkedList<String>();
        List<CrmUser> _users = _friendRepository.getUserInfoList(_userids);
        for (CrmUser u : _users) {
            alias.add(u.getUsername());
        }

        JPushCustomerContent cc = new JPushCustomerContent();

        cc.setPushType("webrelogin");
        cc.setKey(_key);
        cc.setKey("e1117369b0a39e42185042aa");
        cc.setProjectid("3a95002c4cfe848816fc18db");
        _jPushService.sendPushByAliasCustomer(alias, _title, _message, cc);

        //信鸽推送
        XinGeCustomerContent _customerContent = new XinGeCustomerContent();
        _customerContent.setPushType("webrelogin");
        _customerContent.setKey(_key);
        _xingeService.pushCustomerMessageAndroid("", "", _userids, _title, _message, _customerContent);
        _xingeService.pushCustomerMessageIos("", "", _userids, _title, _message, _customerContent);

        return _hasPushed;
    }

}
